package com.eqdd.yiqidian.kotlin.utils

import android.content.Context
import com.bigkoo.pickerview.TimePickerView
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-9-11.
 */
object TimePickerUtil {

    val type1 = booleanArrayOf(true, true, true, true, true, false)
    val type2 = booleanArrayOf(true, true, true, false, false, false)
    val type3 = booleanArrayOf(false, false, false, true, true, false)


    fun timePicker(context: Context, startDate: Date?, endDate: Date?, isUpper: Boolean,
                   type: BooleanArray = booleanArrayOf(true, true, true, true, true, false),
                   body: (date: Date) -> Unit, calculate: (millis: Long) -> Unit = {}) {
        val now = Calendar.getInstance()
        if (type.size != 6) {
            return
        }
        if (isUpper && startDate != null) {
            now.time = startDate
        } else if (endDate != null) {
            now.time = endDate
        }
        TimePickerView
                .Builder(context, TimePickerView.OnTimeSelectListener { date, v ->
                    if (isUpper) {
                        if (endDate != null && date.after(endDate)) {
                            context.toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        body(date)
                    } else {
                        if (startDate != null && date.before(startDate)) {
                            context.toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        body(date)
                    }
                    if (startDate != null && endDate != null) {
                        calculate(endDate.time - startDate.time)
                    }

                })
                .setOutSideCancelable(true)
                .setType(type)
                .setDate(now)
                .build()
                .show()
    }

    fun parseData(string: String?, sdf: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)): Date? {
        if (string.isNullOrBlank()) {
            return null
        }
        return sdf.parse(string)
    }

    fun parseData(hour: Int, minute: Int): Date {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, hour)
        calendar.set(Calendar.MINUTE, minute)
        return calendar.time
    }


}